﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SYS.Common.Broker;
using IBatisNet.Extend;
using IBatisNet.Common.Utilities;
using System.Data;

namespace ExpertMIS.Admin.UserControl
{
    public partial class PagingGridViewWithCheckBox : System.Web.UI.UserControl
    {
        #region Fields
        private static int _pagingSize = int.Parse(ExpertMIS.Codes.Utility.GetEnvironmentValue("PageSize"));
        #endregion

        public event OnDeleteDelegate OnDelete;
        public event OnEditDelegate OnEdit;
        public event OnCheckedValueChangedDelegate OnCheckedValueChanged;

        public string EditClientURL;
        public string DeleteClientScript;
        public string AuditClientURL;
        public string PK;
        public string CheckFieldName;
        public string DeleteClientURL;

        public bool IsLoadData = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(PK)) PK = "F_OID";
            if (string.IsNullOrEmpty(CheckFieldName)) CheckFieldName = "F_IsPassed";
            if (string.IsNullOrEmpty(EditClientURL)) EditClientURL = "{0}";
            if (string.IsNullOrEmpty(DeleteClientScript)) DeleteClientScript = "{0}";
            if (string.IsNullOrEmpty(AuditClientURL)) AuditClientURL = "{0}";
            if (string.IsNullOrEmpty(DeleteClientURL)) AuditClientURL = "{0}";
        }

        protected int Total
        {
            get
            {
                if (!string.IsNullOrEmpty(hfTotal.Value))
                {
                    int tmp = 0;
                    if (int.TryParse(hfTotal.Value, out tmp))
                    {
                        return tmp;
                    }
                    else
                    {
                        return Start = 1;
                    }
                }
                else
                    return Start = 1;
            }
            set
            {
                hfTotal.Value = value.ToString();
            }
        }

        protected int Start
        {
            get
            {
                if (!string.IsNullOrEmpty(hfStart.Value))
                {
                    int tmp = 0;
                    if (int.TryParse(hfStart.Value, out tmp))
                    {
                        return tmp;
                    }
                    else
                    {
                        return Start = 1;
                    }
                }
                else
                    return Start = 1;
            }
            set
            {
                hfStart.Value = value.ToString();
            }
        }


        protected override void Render(HtmlTextWriter writer)
        {
            //if (IsLoadData)
            //{
            //    QueryResult();
            //}
            QueryResult();

            base.Render(writer);
        }

        private void QueryResult()
        {
            string searchKey = string.Empty;

            if (Request["search"] != null)
            {
                searchKey = Request["search"].Replace("{", "").Replace("}", "");
            }

            SYS.Web.Utilities.ColumnGenerator.Generate(gvList, ObjectName, true);

            ObjectBroker brokerInfo = ObjectManagerBroker.GetObjectManagerBroker().GetObjectBrokerByObjectName(ObjectName);
            BaseBroker broker = null;
            if (brokerInfo != null) // 外连了一个Broker对象
            {
                broker = brokerInfo.CreateInstance() as BaseBroker;
            }

            PagingSize pagingSize = new PagingSize();
            pagingSize.Limit = _pagingSize;
            pagingSize.Start = Start;
            pagingSize.SearchKey = broker != null ? broker.ProcessQueryCondition(QueryExpression.CreateQueryExpression(searchKey)) : searchKey;
            pagingSize.SortExpression = string.IsNullOrEmpty(gvList.SortExpression) ? PK + "  DESC" : gvList.SortExpression;
            gvList.DataSource = SQLBuilderBroker.GetSQLBuilderBroker().GetObjectView(ObjectName, pagingSize);

            gvList.AutoGenerateColumns = false;
            gvList.DataBind();
        }

        protected void gvList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        public string ObjectName
        {
            get
            {
                return ViewState["_OBJECTNAME_"] as string;
            }
            set
            {
                ViewState["_OBJECTNAME_"] = value;
            }
        }

        public string FilterString
        {
            get
            {
                return ViewState["_FILTERSTRING_"] as string;
            }
            set
            {
                ViewState["_FILTERSTRING_"] = value;
            }
        }

        protected void gvList_Sorted(object sender, EventArgs e)
        {

        }

        public GridView GetGridView()
        {
            return gvList;
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (gvList.SelectedIndex != -1)
            {
                if ("delete".Equals(e.CommandName))
                {
                    if (OnDelete != null)
                    {
                        DataRow row = (gvList.SelectedRow.DataItem as DataRow);
                        OnDelete(row[PK] as string);
                    }
                }
                else if ("edit".Equals(e.CommandName))
                {
                    if (OnEdit != null)
                    {
                        DataRow row = (gvList.SelectedRow.DataItem as DataRow);
                        OnEdit(row[PK] as string);
                    }
                }
                else if ("passed".Equals(e.CommandName))
                {
                    if (OnCheckedValueChanged != null)
                    {
                        DataRow row = (gvList.SelectedRow.DataItem as DataRow);
                        bool bCheck = false;
                        if (row[CheckFieldName].ToString() == "1" || row[CheckFieldName].ToString().ToLower() == "true")
                        {
                            bCheck = true;
                        }
                        OnCheckedValueChanged(row[PK] as string, bCheck);
                    }
                }
            }
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView row = e.Row.DataItem as DataRowView;
                ImageButton ibEdit = e.Row.FindControl("ibEdit") as ImageButton;
                ibEdit.PostBackUrl = string.Format(EditClientURL, row[PK]);

                ImageButton ibDelete = e.Row.FindControl("ibDelete") as ImageButton;
                ibDelete.PostBackUrl = string.Format(DeleteClientURL, row[PK]);
                ibDelete.OnClientClick = string.Format(DeleteClientScript, row[PK]);
                e.Row.CssClass = "gridview_row";
            }
        }

        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cbSelectedAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvList.Rows)
            {
                CheckBox cbRow = row.FindControl("cbChecked") as CheckBox;
                CheckBox cbHeader = gvList.HeaderRow.FindControl("cbSelectedAll") as CheckBox;

                if (cbRow != null && cbHeader != null)
                {
                    cbRow.Checked = cbHeader.Checked;
                }
            }
        }

        /// <summary>
        /// 获取审核通过记录的主键列表
        /// </summary>
        /// <returns></returns>
        public IList<string> GetCheckedRecordPKArray()
        {
            IList<string> selectedOIDs = new List<string>();
            foreach (GridViewRow row in gvList.Rows)
            {
                DataRowView rowView = row.DataItem as DataRowView;
                if (rowView != null)
                {
                    CheckBox cbRow = row.FindControl("cbChecked") as CheckBox;
                    if (cbRow.Checked)
                    {
                        selectedOIDs.Add(rowView[PK].ToString());
                    }
                }
            }

            return selectedOIDs;
        }

        protected void lbPrior_Click(object sender, EventArgs e)
        {
            if (Start - 1 > 0)
            {
                Start--;
            }
        }

        protected void lbNext_Click(object sender, EventArgs e)
        {
            if (Start + 1 <= (int)System.Math.Ceiling((double)Total / _pagingSize))
            {
                Start++;
            }
        }
    }
}